<!--历史数据-->
<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>

      <a-card
        :bordered="false"
        title="温度饮水关系情况"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="temperatureHumidityChart"
          style="height: 362px;"
          :option="temperatureHumidityChartOption"/>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="pdddId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space />
          </template>

          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openDetail(record)">详情</a>
                <a-divider type="vertical" v-permission="['PROPERTY_DEVICELIST_MGR_DRINKHEARTING_DATA_DEL_BUTTON']" />
                <div v-permission="['PROPERTY_DEVICELIST_MGR_DRINKHEARTING_DATA_DEL_BUTTON']">
                  <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                    <a class="ele-text-danger">删除</a>
                  </a-popconfirm>
                </div>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

    <!-- 编辑弹窗 -->
    <DeviceDrinkheartingDataDetail v-if="showDetail" v-model:visible="showDetail" :data="current"/>
  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import DeviceDrinkheartingDataDetail from './drinkhearting-data-detail.vue';
import moment from 'moment';
import { message } from 'ant-design-vue';
import {DeviceDrinkheatingDataApi} from "@/api/property/drinkhearting/DeviceDrinkheatingDataApi";


use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
]);
provide(THEME_KEY, ChartTheme);

export default {
  name: 'DeviceDrinkheartingData',
  components: {
    DeviceDrinkheartingDataDetail,
    VChart
  },
  props: {
    data: Object
  },
  async mounted() {
    this.getTemperatureHumidityData();
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '创建时间',
          dataIndex: 'createTime',
          fixed: 'left'
        },
        {
          title: '信号强度',
          dataIndex: 'signalLevel',
          fixed: 'left'
        },
        {
          title: '空气温度℃',
          dataIndex: 'envTemperature',
          fixed: 'left'
        },
        {
          title: '进水温度℃',
          dataIndex: 'influentTemperature',
          fixed: 'left'
        },
        {
          title: '出水温度℃',
          dataIndex: 'effluentTemperature',
          fixed: 'left'
        },
        {
          title: '进水瞬时流量L/h',
          dataIndex: 'influentMomentFlow'
        },
        {
          title: '出水瞬时流量L/h',
          dataIndex: 'effluentMomentFlow'
        },
        {
          title: '进水累计流量(m³)',
          dataIndex: 'influentFlow',
          customRender: function(row) {
            return (row.record.influentFlow * 0.01).toFixed(2);
          }
        },
        {
          title: '出水累计流量(m³)',
          dataIndex: 'effluentFlow',
          customRender: function(row) {
            return (row.record.effluentFlow * 0.01).toFixed(2);
          }
        },
        {
          title: '饮水量(m³)',
          dataIndex: 'effluentFlow',
          customRender: function(row) {
            return ((row.record.cycleInfluentFlow - row.record.cycleEffluentFlow) * 0.01).toFixed(2);
          }
        },
        {
          title: '室外温度℃',
          dataIndex: 'outTemperature'
        },
        {
          title: '室外湿度%RH',
          dataIndex: 'outHumidity'
        },
        {
          title: '室外光照lux',
          dataIndex: 'outBeam'
        },
        {
          title: '室外风向',
          dataIndex: 'outWindDirection',
          customRender: function(row) {
            if (row.record.outWindSpeed > 0) {
              if (row.text == 0) {
                return "北风";
              } else if (row.text == 1) {
                return "东北风";
              } else if (row.text == 2) {
                return "东风";
              } else if (row.text == 3) {
                return "东南风";
              } else if (row.text == 4) {
                return "南风";
              } else if (row.text == 5) {
                return "西南风";
              } else if (row.text == 6) {
                return "西风";
              } else if (row.text == 7) {
                return "西北风";
              }
            } else {
              return "未知";
            }
          }
        },
        {
          title: '室外风速m/s',
          dataIndex: 'outWindSpeed'
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center',
          fixed: 'right'
        }
      ],
      // 表格搜索条件
      where: {"recordId" : this.data.recordId},
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showDetail: false,
      temperatureHumidityData: [],
    }
  },
  computed: {
    // 最近1小时温度情况折线图配置
    temperatureHumidityChartOption() {
      /*if (!this.visitHourData.length) {
        return null;
      }*/
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['进水温度', '出水温度', '空气温度', '室外温度', '饮水量'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.temperatureHumidityData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '温度 (°C)'
          },
          {
            type: 'value',
            name: '饮水量 (m³)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '进水温度',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: this.temperatureHumidityData.map(d => d.influentTemperature),
            yAxisIndex: 0,
          },
          {
            name: '出水温度',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: this.temperatureHumidityData.map(d => d.effluentTemperature),
            yAxisIndex: 0,
          },
          {
            name: '空气温度',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: this.temperatureHumidityData.map(d => d.envTemperature),
            yAxisIndex: 0,
          },
          {
            name: '室外温度',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: this.temperatureHumidityData.map(d => d.outTemperature),
            yAxisIndex: 0,
          },
          {
            name: '饮水量',
            type: 'line',
            smooth: true,
            symbol: 'none',
            data: this.temperatureHumidityData.map(d => d.total),
            yAxisIndex: 1,
          }
        ]
      }
    },
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
      this.getTemperatureHumidityData();
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reset() {
      this.where.recordId = this.data.recordId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    async remove(row) {
      const result = await DeviceDrinkheatingDataApi.delete({ pdddId: row.pdddId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    openDetail(row) {
      this.current = row;
      this.showDetail = true;
    },

    getTemperatureHumidityData(){
      let params = {
        searchBeginTime : moment().subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss'),
        searchEndTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        recordId : this.data.recordId,
        sortBy : "asc",
        orderBy : "create_time"
      };
      if (this.where.searchBeginTime && this.where.searchEndTime) {
        params.searchBeginTime = this.where.searchBeginTime;
        params.searchEndTime = this.where.searchEndTime;
      }

      DeviceDrinkheatingDataApi.list(params).then(list => {
        let _temperatureHumidityData = [];
        if (list && list.length > 0) {
          list.forEach(function(item) {
            let formatItem = {
              time : item.createTime.substr(0, 16),
              influentTemperature : item.influentTemperature,
              effluentTemperature : item.effluentTemperature,
              envTemperature : item.envTemperature,
              total : ((item.cycleInfluentFlow - item.cycleEffluentFlow) * 0.01).toFixed(2),
              outTemperature : item.outTemperature
            };
            _temperatureHumidityData.push(formatItem);
          });
        } else {
          let last20 = moment().subtract(20, 'minute');
          let last10 = moment().subtract(10, 'minute');
          let last5 = moment().subtract(5, 'minute');
          _temperatureHumidityData.push({
            time : last20.format('YYYY-MM-DD HH:mm'),
            influentTemperature : 0,
            effluentTemperature : 0,
            envTemperature : 0,
            total : 0,
            outTemperature : 0
          });
          _temperatureHumidityData.push({
            time : last10.format('YYYY-MM-DD HH:mm'),
            influentTemperature : 0,
            effluentTemperature : 0,
            envTemperature : 0,
            total : 0,
            outTemperature : 0
          });
          _temperatureHumidityData.push({
            time : last5.format('YYYY-MM-DD HH:mm'),
            influentTemperature : 0,
            effluentTemperature : 0,
            envTemperature : 0,
            total : 0,
            outTemperature : 0
          });
        }
        this.temperatureHumidityData = _temperatureHumidityData;
      });
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceDrinkheatingDataApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    activated() {
      ['temperatureHumidityChart'].forEach((name) => {
        this.$refs[name].resize();
      });
    }
  }
};
</script>
